package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.enums.SexEnum;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Voice;
import com.tanhua.dubbo.service.IdService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService(version = "1.0.0")
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private UserInfoApi userInfoApi;

    @Override
    public String saveVideo(Voice voice) {

        //校验
        if (!ObjectUtil.isAllNotEmpty(voice.getUserId(), voice.getSoundUrl())) {
            return null;
        }

        voice.setId(ObjectId.get());
        voice.setVid(this.idService.createVoiceId(IdType.VOICE)); //自增长的id
        voice.setCreated(System.currentTimeMillis());
        voice.setSeeType(1);

        this.mongoTemplate.save(voice);
        return voice.getId().toString();
    }


    @Override
    public Voice queryVoiceById(String voiceId) {
        return this.mongoTemplate.findById(new ObjectId(voiceId), Voice.class);
    }


    @Override
    public List<Voice> queryAllVoice() {
        return this.mongoTemplate.findAll(Voice.class);
    }


    /**
     * 根据当前用户id，给出推荐语音
     * @param myId
     * @return
     */
    @Override
    public Voice receiveRecommendVoice(Long myId) {

        List<Voice> voiceList = this.queryAllVoice();
        if (CollUtil.isEmpty(voiceList)){
            return null;
        }

        long ranVid = RandomUtil.randomLong(1, voiceList.size()+1);

        //尽量选取距离接收时创建时间间隔较短的
        Query query = Query.query(Criteria.where("vid").is(ranVid))
                .with(Sort.by(Sort.Order.desc("created"))).limit(1);
        return this.mongoTemplate.findOne(query,Voice.class);
    }
}
